package com.haoshuang.zhouzhoubang.ui.page.account.login

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import com.azhon.appupdate.listener.OnButtonClickListener
import com.azhon.appupdate.manager.DownloadManager
import com.blankj.utilcode.util.AppUtils
import com.haoshuang.zhouzhoubang.MyApp
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.config.Config
import com.haoshuang.zhouzhoubang.config.URLConstants
import com.haoshuang.zhouzhoubang.databinding.ActivityLoginBinding
import com.haoshuang.zhouzhoubang.model.event.WeChatLoginEvent
import com.haoshuang.zhouzhoubang.ui.adapter.ViewPagerAdapter
import com.haoshuang.zhouzhoubang.ui.dialog.AgreementDialog
import com.haoshuang.zhouzhoubang.ui.dialog.ConfirmDialog
import com.haoshuang.zhouzhoubang.ui.dialog.UpdateVersionDialog
import com.haoshuang.zhouzhoubang.ui.page.account.login.account.AccountLoginFragment
import com.haoshuang.zhouzhoubang.ui.page.account.login.code.CodeLoginFragment
import com.haoshuang.zhouzhoubang.ui.page.help.login.LoginHelpActivity
import com.haoshuang.zhouzhoubang.ui.page.main.MainActivity
import com.haoshuang.zhouzhoubang.utils.EnvironmentUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lnkj.jialubao.utils.AccountUtils
import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.NetworkUtil.url
import com.mufeng.libs.utils.finishPage
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.gone
import com.mufeng.libs.utils.view.visible


/**
 *
 */
class LoginActivity : BaseVMActivity<LoginViewModel, ActivityLoginBinding>(),
    OnButtonClickListener {

    companion object {
        fun launch(context: Context) {
            context.startPage<LoginActivity>()
        }
    }

    private val fragments = arrayListOf<Fragment>()
    private val titles = arrayListOf("账号登录", "验证码登录")

    override fun initView(savedInstanceState: Bundle?) {

        if (Config.isTestEnvironment) {
            // 切换环境
            EnvironmentUtils.changeEnvironment(binding.tvEnvironment, mActivity)
            binding.tvEnvironment.text =
                "${if (AccountUtils.isTestEnvironment) "测试环境" else "正式环境"}\n${URLConstants.baseUrl}"
            binding.tvEnvironment.visible()
        }else{
            binding.tvEnvironment.gone()
        }


        binding.tvHelp.clickWithTrigger {
            // 打开帮助列表
            startPage<LoginHelpActivity>()
        }

        initViewPager()

        if (!AccountUtils.isAgreementDialog){
            XPopup.Builder(mActivity)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .asCustom(AgreementDialog(mActivity))
                .show()
        }else{
            MyApp.instance.initJpush()
        }
    }

    private fun initViewPager() {
        fragments.clear()
        fragments.add(AccountLoginFragment.getInstance())
        fragments.add(CodeLoginFragment.getInstance())

        val adapter = ViewPagerAdapter(supportFragmentManager, lifecycle, fragments)
        binding.viewPager.adapter = adapter

        binding.slidingTabLayout.setViewPager2(binding.viewPager, titles)
    }

    override fun initData() {
        vm.getAppVersions()
    }

    override fun onResume() {
        super.onResume()
    }

    override fun startObserve() {

        LiveEventBus.get(WeChatLoginEvent::class.java).observe(this){
            Log.e("WeChatLoginEvent", "code:${it?.code}")
            // 微信登录
            vm.wechatLogin(it.code)
        }

        vm.getAppVersionsData.observeState(this) {
            onSuccess {
                if (it != null){
                    val manager = DownloadManager.Builder(mActivity).run {
                        apkUrl(it.android_download_url!!)
                        apkName("zhouzhoubang.apk")
                        smallIcon(R.mipmap.logo)
                        showNewerToast(false)
                        apkVersionCode(it.versions_code!!)
                        apkVersionName("V ${it.versions_no}")
                        apkDescription(it.content!!)
                        enableLog(true)
                        jumpInstallPage(true)
                        dialogButtonTextColor(Color.WHITE)
                        showNotification(true)
                        showBgdToast(true)
                        forcedUpgrade(it.is_force == 1)
                        build()
                    }
                    manager.download()
                }
            }
        }

        vm.wechatLoginData.observeState(this){
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                toast("登录成功")
                AccountUtils.isTokenErrorJumpLoginPage = true
                AccountUtils.user = it?.data
                AccountUtils.token = it?.data?.token ?: ""
                startPage<MainActivity>()
                finish()
            }
        }

    }

    override fun onButtonClick(id: Int) {

    }

}